# Copyright [2011] [Ilya Rudakov]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.contrib.auth.decorators import login_required

from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from job_manager.forms import UploadFeedForm, CreateFeedGroupForm

from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
from django.core import serializers
from json.encoder import JSONEncoder
from job_manager.services.job_runner_service import invoke_job_runner, do_interrupt_job
from job_manager.services.state_check_service import get_feed_state

from job_manager.services.storage_service import *

POST = "POST"
GET= "GET"

@login_required
def index(request):
    return render_to_response("index.html", {
        "create_feed_group_form": CreateFeedGroupForm(),
        "upload_feed_form": UploadFeedForm(),
        "feed_group_list": FeedGroup.objects.all(),
    }, context_instance=RequestContext(request))

@csrf_protect
def create_feed_group(request):
    if request.method == POST:
        create_job_group_form = CreateFeedGroupForm(request.POST)
        if create_job_group_form.is_valid():
            feed_group_name = create_job_group_form.cleaned_data['name']
            add_feed_group(name=feed_group_name)
            return HttpResponseRedirect("/jm/index")
        else:
            return render_to_response("index.html", {
                "create_feed_group_form": create_job_group_form,
                "upload_feed_form": UploadFeedForm(),
                "feed_group_list": FeedGroup.objects.all(),
            }, context_instance=RequestContext(request))

@login_required
def delete_job_group(request, job_group_id):
    delete_job_group_(job_group_id)
    return HttpResponseRedirect("/jm/index")

@csrf_protect
def upload_feed(request):
    if request.method == POST:
        upload_job_form = UploadFeedForm(request.POST, request.FILES)
        if upload_job_form.is_valid():
            feed_file = upload_job_form.cleaned_zipfile()
            feed_name, description, feed_group = upload_job_form.cleaned_data['name'], upload_job_form.cleaned_data['description'], upload_job_form.cleaned_data['feed_group']
            add_feed(name=feed_name, description=description, feed_group=feed_group, file=feed_file, user=request.user)
            return HttpResponseRedirect("/jm/index")
        else:
            return render_to_response("index.html", {
                "create_feed_group_form": CreateFeedGroupForm(),
                "upload_feed_form": upload_job_form,
                "feed_group_list": FeedGroup.objects.all(),
            }, context_instance=RequestContext(request))

def sample_ajax(request):
    data = serializers.serialize("json", Feed.objects.all())
    return HttpResponse(data, mimetype="application/javascript")

def start_feed(request):
    if request.is_ajax():
        feed_id = request.POST.get("feed_id")
        invoke_job_runner(feed_id, request.user)
        json_response = JSONEncoder().encode({"message": "Feed(id=%s) started!" % feed_id})
        return HttpResponse(json_response, mimetype="application/javascript")

def interrupt_feed(request):
    if request.is_ajax():
        feed_id = request.POST.get("feed_id")
        do_interrupt_job(feed_id)
        json_response = JSONEncoder().encode({"message": "Feed(id=%s) interrupted!" % feed_id})
        return HttpResponse(json_response, mimetype="application/javascript")

def get_feed_states(request):
    if request.is_ajax():
        feed_ids = request.GET.getlist('feed_ids[]')

        feed_state_array = []
        for feed_id in feed_ids:
            feed_state = get_feed_state(feed_id)
            feed_state_array.append(feed_state)

        json_response = JSONEncoder().encode(feed_state_array)
        return HttpResponse(json_response, mimetype="application/javascript")

def delete_feed(request):
    result = False
    if request.is_ajax():
        feed_id = request.POST.get("feed_id")
        result = del_feed(feed_id)
    json_response = JSONEncoder().encode({"result": result})
    return HttpResponse(json_response, mimetype="application/javascript")

def change_group(request):
    if request.is_ajax():
        feed_id = request.POST.get("feed_id")
        receiver_group_id = request.POST.get("receiver_group_id")
        set_group(feed_id, receiver_group_id, request.user)
    json_response = JSONEncoder().encode({"result": True})
    return HttpResponse(json_response, mimetype="application/javascript")

def update_job_description(request):
    if request.is_ajax():
        job_id, description = request.POST.get("job_id"), request.POST.get("description")
        update_job_description_(job_id, description)
    return HttpResponse({"message": "OK"}, mimetype="application/javascript")

def update_job_name(request):
    if request.is_ajax():
        job_id, name = request.POST.get("job_id"), request.POST.get("name")
        update_job_name_(job_id, name)
    return HttpResponse({"message": "OK"}, mimetype="application/javascript")

def update_job_group_name(request):
    if request.is_ajax():
        job_group_id, name = request.POST.get("job_group_id"), request.POST.get("name")
        update_job_group_name_(job_group_id, name)
    return HttpResponse({"message": "OK"}, mimetype="application/javascript")
